package com.thread.threadpool;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.common.collect.Lists;
import com.thread.model.entity.UserDemo;
import com.thread.model.entity.test1.UserAge;
import com.thread.model.entity.test1.UserName;
import com.thread.model.mapper.UserAgeMapper;
import com.thread.model.service.IUserAgeService;
import com.thread.model.service.IUserNameService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ccubee
 * @since 21-3-31 21:10
 */
@Slf4j
@DS("test1")
@Service
@RequiredArgsConstructor
public class RunnablePoolDemo {

    private final IUserNameService userNameService;
    private final IUserAgeService userAgeService;


    private static final int MIN_THREAD_SIZE = 50;
    private static final int MAX_THREAD_SIZE = 200;
    private static final int KEEP_ALIVE_TIME = 3;


    // 自定义线程池

    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            MIN_THREAD_SIZE,
            MAX_THREAD_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(12),
            new ThreadPoolExecutor.CallerRunsPolicy());



    @DS("test1")
    public void userMove(List<UserDemo> list) {
        try {
            long start = System.currentTimeMillis();
            List<List<UserDemo>> partList = Lists.partition(list, 1000);
            for (List<UserDemo> demoList : partList) {
                threadPoolExecutor.execute(new UserMove(userNameService,userAgeService, demoList));
            }
            long end = System.currentTimeMillis();
            while (!threadPoolExecutor.isTerminated()) {
                System.out.print("线程任务执行中，当前任务数：");
                System.out.println(threadPoolExecutor.getQueue().size());
                Thread.sleep(1000);
            }
            log.info("使用时间位 {}", end -start);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }




}
